﻿@page "/PlotlyBlazorLineChartTest2"
@inject IJSRuntime jsRuntime

<h3>PlotlyBlazorLineChartTest2</h3>

@using Plotly.Blazor
@using Plotly.Blazor.Traces

<div id="plotly-chart" style="width:100%; height:500px;"></div>

<button @onclick="AddDefaultRect" class="btn btn-primary mt-2">添加矩形</button>
<button @onclick="ClearAllRects" class="btn btn-danger mt-2">清除所有</button>
<button @onclick="RemoveLastRect" class="btn btn-warning mt-2">删除最后一个</button>

<script src="./plotly-latest.min.js"></script>
<script src="./plotlyInterop.js"></script>

@code {
    private DotNetObjectReference<PlotlyBlazorLineChartTest2>? dotNetRef;
    private bool isInitialized = false;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await jsRuntime.InvokeVoidAsync("import", "./plotlyInterop.js");
        if (firstRender && !isInitialized)
        {
            try
            {
                dotNetRef = DotNetObjectReference.Create(this);

                // 示例数据
                var xValues = Enumerable.Range(0, 100).Select(i => (double)i).ToArray();
                var yValues = xValues.Select(x => Math.Sin(x / 10.0) * 10).ToArray();

                // 初始化图表
                isInitialized = await jsRuntime.InvokeAsync<bool>(
                    "plotlyInterop.initialize",
                    "plotly-chart",
                    xValues,
                    yValues,
                    dotNetRef);

                if (!isInitialized)
                {
                   
                }
            }
            catch (Exception ex)
            {
                
            }
        }
    }

    // 添加默认矩形
    private async Task AddDefaultRect()
    {
        await jsRuntime.InvokeVoidAsync("plotlyInterop.addSelectionRect", 0, 10);
    }

    // 清除所有矩形
    private async Task ClearAllRects()
    {
        await jsRuntime.InvokeVoidAsync("plotlyInterop.clearAllSelections");
    }

    // 删除最后一个矩形
    private async Task RemoveLastRect()
    {
        await jsRuntime.InvokeVoidAsync("plotlyInterop.removeLastShape");
    }

    // 获取当前所有矩形
    private async Task LogCurrentShapes()
    {
        var shapes = await jsRuntime.InvokeAsync<string>("plotlyInterop.getCurrentShapes");
    }

    [JSInvokable]
    public Task OnShapeAdded(double x0, double x1)
    {
        return Task.CompletedTask;
    }

    public async ValueTask DisposeAsync()
    {
        if (isInitialized)
        {
            await jsRuntime.InvokeVoidAsync("plotlyInterop.clearAllSelections");
        }
        dotNetRef?.Dispose();
    }
}
